package com.cherry.ssm.client.service.impl;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.cherry.ssm.client.dao.ClientMapper;
import com.cherry.ssm.client.service.ClientService;
import com.cherry.ssm.util.Constant;
import com.cherry.ssm.util.RandomMD5;
import com.cherry.ssm.util.model.SsoDictVal;
import com.cherry.ssm.util.service.SsoDictValService;


@Service
public class ClientServiceImpl implements ClientService {

	@Autowired
    private ClientMapper clientMapper;
	
	@Autowired
    private SsoDictValService ssoDictValService;
	
	private static final Logger log = LoggerFactory.getLogger(ClientServiceImpl.class);
	
	
	/**
	 * 通过HttpServletRequest获取请求源头的真实ip
	 * 通过真实ip在数据库中判断是否有接入权限
	 * 如果有,则将真实ip加密返回给客户端
	 * 同时在数据库中将这条记录改为true
	 * @param request
	 * @param session
	 * @return
	 */
	public HttpEntity authentication(HttpServletRequest request, HttpSession session){
		System.out.println("/authentication");
		
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
		System.out.println("ip:   "+ip);
		
		List<SsoDictVal>  ssoDictValList = this.ssoDictValService.getEntityByTypeCodeValCode(Constant.CLIENT_TYPE_CODE,ip);
		if(ssoDictValList != null && ssoDictValList.size() == 1){
	        String str = null;
	        try {
	        	//  先用sso的密钥加密得到的结果再用客户端的密钥加一次密,客户端进入登陆页面的时候需要先自己解密一次
	        	str = RandomMD5.aesEncrypt(ip,Constant.AES_KEY_SSO);
			} catch (Exception e) {
				e.printStackTrace();
			}
	        SsoDictVal ssoDictVal = ssoDictValList.get(0);
	        ssoDictVal.setValDescription("true");
	        boolean bool = this.ssoDictValService.updateSsoDictVal(ssoDictVal);
	        if(bool){
	        	log.info("客户端接入权限请求完成");
				return new ResponseEntity(str, HttpStatus.OK);
	        }else{
	        	log.info("当前客户端请求有效期设置失败");
				return new ResponseEntity("settingfalse", HttpStatus.OK);
	        }
		}else if(ssoDictValList != null && ssoDictValList.size() > 1){
			log.error("有多个客户端ip对应的请求配置");
			return new ResponseEntity("clientPrompt", HttpStatus.OK);
		}else{
			log.error("未获取到客户端ip对应的请求配置");
			return new ResponseEntity("notSettingip", HttpStatus.OK);
		}
		
		
	}
	
	
	/**
	 * 从客户端,请求服务端登陆页面
	 * 通过/authentication接口返回的str(加密后的真实ip)
	 * 解密后在数据库中判断是否做了接入权限的验证
	 * 做了则将这条数据改成false,跳转登陆页,没做则跳转非法登陆
	 * @param client_url   客户端被拦截的请求
	 * @param intercept_url   完成登陆后重新定向到客户端的接口
	 * @param str  通过/authentication接口返回的str(加密后的真实ip)
	 * @return
	 */
	public String loginpage(String client_url, String intercept_url, String str, HttpServletRequest request, HttpSession session){
		System.out.println("/loginpage");
		
		if(str != null && str.length() > 0){
			String ip = null;
			try {
				ip = RandomMD5.aesDecrypt(str,Constant.AES_KEY_SSO);
			} catch (Exception e) {
				e.printStackTrace();
			}
			List<SsoDictVal>  ssoDictValList = this.ssoDictValService.getEntityByTypeCodeValCode(Constant.CLIENT_TYPE_CODE,ip);
			if(ssoDictValList != null && ssoDictValList.size() == 1){
				SsoDictVal ssoDictVal = ssoDictValList.get(0);
				if(ssoDictVal.getValDescription().equals("true")){
					ssoDictVal.setValDescription("false");
			        boolean bool = this.ssoDictValService.updateSsoDictVal(ssoDictVal);
			        session.setAttribute(Constant.REQUEST_IP,str);
		        	session.setAttribute(Constant.CLIENT_URL_KEY,client_url);
		        	session.setAttribute(Constant.CLIENT_INTERCEPT_KEY,intercept_url);
		        	if(bool){
		        		return "login/login";
		        	}else{
		        		return "login/unlawful";
		        	}
				}else{
					return "login/unlawful";
				}
			}else if(ssoDictValList != null && ssoDictValList.size() > 1){
	        	return "login/client_prompt";
	        }else{
	        	return "login/notSetting_ip";
	        }
		}else{
			return "login/unlawful";
		}
	}
	
	
}
